package com.ybox.gateway.service.impl;

import cloud.tianai.captcha.common.constant.CaptchaTypeConstant;
import cloud.tianai.captcha.spring.application.ImageCaptchaApplication;
import cloud.tianai.captcha.spring.plugins.secondary.SecondaryVerificationApplication;
import cloud.tianai.captcha.spring.vo.CaptchaResponse;
import cloud.tianai.captcha.spring.vo.ImageCaptchaVO;
import cloud.tianai.captcha.validator.common.model.dto.ImageCaptchaTrack;
import com.ybox.common.core.exception.CaptchaException;
import com.ybox.gateway.service.ValidateSwipeService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 验证码实现处理
 *
 * @author ych
 */
@Component
public class ValidateSwipeServiceImpl implements ValidateSwipeService {


    @Autowired
    private ImageCaptchaApplication imageCaptchaApplication;

    /**
     * 生成验证码
     */

    @Override
    public CaptchaResponse<ImageCaptchaVO> createCaptcha(String type) {
        if (StringUtils.isBlank(type)) {
            type = CaptchaTypeConstant.SLIDER;
        }
        CaptchaResponse<ImageCaptchaVO> response = imageCaptchaApplication.generateCaptcha(type);
        return response;
    }

    /**
     * 校验验证码
     */
    @Override
    public Boolean checkCaptcha(String id, ImageCaptchaTrack imageCaptchaTrack) {
        if (StringUtils.isEmpty(id)) {
            throw new CaptchaException("验证码id不能为空");
        }
        if (ObjectUtils.isEmpty(imageCaptchaTrack)) {
            throw new CaptchaException("验证参数不能为空");
        }
        boolean matching = imageCaptchaApplication.matching(id, imageCaptchaTrack);

        if (!matching) {
            throw new CaptchaException("验证错误");
        }
        return true;
    }

    /**
     * 二次验证，一般用于机器内部调用，这里为了方便测试
     *
     * @param id id
     * @return boolean
     */
    @Override
    public Boolean check2Captcha(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new CaptchaException("验证码id不能为空");
        }
        // 如果开启了二次验证
        if (imageCaptchaApplication instanceof SecondaryVerificationApplication) {
            boolean b = ((SecondaryVerificationApplication) imageCaptchaApplication).secondaryVerification(id);
            if (!b){
                throw new CaptchaException("验证错误");
            }
        }
        return true;
    }
}
